<template>
<div :class="[$style.container]">
  <remote-script src="http://rescdn.qqmail.com/node/ww/wwopenmng/js/sso/wwLogin-1.0.0.js" id="wecom" @load="onLoad" @error="onError"></remote-script>
  <div id="wecom_container"></div>
</div>
</template>

<script lang="ts">
import { AppModule } from '@/store'
import { expr } from '@/utils/url'
import { Component, Emit, Prop, Vue } from 'vue-property-decorator'

@Component
export default class WecomQrcode extends Vue {
  @Prop({ type: String, default: 'login' }) action!: 'login' | 'bind'

  @AppModule.State properties!: any

  get returnUrl () {
    const url = new URL(location.href)
    // const p = this.action === 'login' ? url.searchParams.get('returnUrl') : url.href
    // return p ? encodeURI(p) : p
    // return url
    const u = url.protocol + (url.host || '') + (url.pathname || '')
    return encodeURI(u)
  }

  // get authorizeUrl () {
  //   return 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize'
  // }

  get appid () {
    return this.properties?.weCom?.appKey
  }

  get agentid () {
    return this.properties?.weCom?.agentId
  }

  get redirectBaseUrl () {
    return this.properties?.deploy?.externalAccountWeb || expr(this.properties?.deploy?.accountWeb)
  }

  get redirectUrl () {
    const url = `${this.redirectBaseUrl}/after-authorize?returnUrl=${this.returnUrl || ''}&type=wecom&action=${this.action}`
    return encodeURIComponent(url)
  }

  // get goto () {
  //   const state = 'rawa'
  //   return encodeURIComponent(`${this.authorizeUrl}?appid=${this.appid}&response_type=code&scope=snsapi_login&state=${state}&redirect_uri=${this.redirectUrl}`)
  // }

  onLoad () {
    const win = window as any
    const wecom = win.WwLogin({
      id: 'wecom_container',
      appid: this.appid,
      agentid: this.agentid,
      // eslint-disable-next-line
      redirect_uri: this.redirectUrl,
      state: 'rawa'
    })
  }

  onError (e: Event) {
    this.$message.error('加载微信失败: ' + ((e as any)?.message || ''))
  }
}
</script>

<style lang="scss" module>
.container {
  // padding: 12px;
}
</style>
